package com.alfy.sbdemo.websocketdemo.demo2;

import org.java_websocket.client.WebSocketClient;
import org.java_websocket.handshake.ServerHandshake;

import java.net.URI;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * 自定义 WebSocket 客户端
 *
 * @author pengyf
 * @date 2024/05/27
 */
public class WebSocketClientDemo extends WebSocketClient {

    /**
     * 用来接收数据
     */
    private String excptMessage;

    /**
     * 线程安全的 Boolean -是否受到消息
     */
    public AtomicBoolean hasMessage = new AtomicBoolean(false);

    /**
     * 线程安全的 Boolean -是否已经连接
     */
    private AtomicBoolean hasConnection = new AtomicBoolean(false);

    /**
     * 构造方法
     *
     * @param serverUri
     */
    public WebSocketClientDemo(URI serverUri) {
        super(serverUri);
        System.out.println("WebSocketClientDemo init: " + serverUri.toString());
    }

    /**
     * 打开连接是方法
     *
     * @param serverHandshake
     */
    @Override
    public void onOpen(ServerHandshake serverHandshake) {
        System.out.println("WebSocketClientDemo open 事件 ~~~");
    }

    /**
     * 收到消息时
     *
     * @param message
     */
    @Override
    public void onMessage(String message) {
        hasMessage.set(true);
        System.out.println("WebSocketClientDemo message 事件, 接收消息: " + message);
        excptMessage = message;
    }

    /**
     * send message
     *
     * @param message message
     */
    public void sendMessage(String message) {
        this.send(message);
        System.out.println("已发送消息：" + message);
    }

    /**
     * 当连接关闭时
     *
     * @param code   code
     * @param reason reason
     * @param remote remote
     */
    @Override
    public void onClose(int code, String reason, boolean remote ) {
        this.hasConnection.set(false);
        this.hasMessage.set(false);
        System.out.println("WebSocketClientDemo close 事件, code: " + code);
    }

    /**
     * 发生 error 事件
     *
     * @param exception
     */
    @Override
    public void onError(Exception exception) {
        System.out.println("WebSocketClientDemo error事件, ex:" + exception);
    }

    /**
     * connect
     */
    @Override
    public void connect() {
        // 是否已经连接，否才可以连接
        if (!this.hasConnection.get()) {
            super.connect();
            hasConnection.set(true);
        }
    }

    /**
     * 获取接收到的信息
     *
     * @return
     */
    public String getExcptMessage() {
        if (excptMessage != null) {
            String message = new String(excptMessage);
            excptMessage = null;
            return message;
        }
        return null;
    }
}


